import React from 'react';
import { Breadcrumb, Icon, Input, Button, Table, Modal, Select, Upload, message, Form } from 'antd';
import './banner.less';
import $ from 'jquery';
import Config from '../../common/config';
const config = new Config();
const FormItem = Form.Item;
const token = sessionStorage.getItem('token');
const Option = Select.Option;
//banner信息的表单
const BannerForm = Form.create()(
    (props) => {
        const { visible, saveBanner, handleCancel, form,openLength, normFile, beforeUpload, fileList, previewImg, previewVisible, cancelPreview, previewImage,BannerId,isOpen } = props;
        const { getFieldDecorator } = form;
        const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 }, };
        return (
            <Modal
                className="banner-modal"
                title="banner管理"
                visible={visible}
                okText="保存"
                onOk={saveBanner}
                onCancel={handleCancel}
                maskClosable={false}
            >
                <Form layout="vertical">
                    <FormItem {...formItemLayout} label="名称" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                        {getFieldDecorator('t_bannerName', {
                            rules: [{ required: true, max: 20, message: '请输入名称，不超过20个字' }],
                        })(
                            <Input placeholder="请输入名称" />
                        )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="链接地址" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                        {getFieldDecorator('t_urlPath', {
                            rules: [{  max: 200, message: '不超过200个字' }],
                        })(
                            <Input placeholder="请输入主题图片链接地址" />
                        )}
                    </FormItem>
                    {BannerId? isOpen==1?<FormItem {...formItemLayout} label="排序" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                        {getFieldDecorator('t_sort', {
                            rules: [{ required: true, message: '请选择' }],
                        })(
                            <Select placeholder='请选择'>
                                {
                                    Array.from({length:openLength},(v,i)=>i).map((item,i)=> <Option value={(i+1).toString()} key={i}>{i+1}</Option>)
                                }
                            </Select>
                        )}
                    </FormItem>:'':''}
                    <FormItem {...formItemLayout} label="banner照片" style={{ minHeight: '120px', marginBottom: 0 }}>
                        <div>
                            {getFieldDecorator('Filedata', {
                                valuePropName: 'fileList', getValueFromEvent: normFile,
                                rules: [{ required: true, message: '请上传banner照片' }],
                            })(
                                <Upload
                                    accept="image/*"
                                    name="img"
                                    action={config.integratedBack1 + "/bannerImg"}
                                    beforeUpload={beforeUpload}
                                    listType="picture-card"
                                    className="upload-list-inline"
                                    style={{ float: 'left' }}
                                    onPreview={previewImg}
                                >
                                    {
                                        fileList.length >= 1 ? null :
                                            <div>
                                                <Icon type="plus" />
                                                <div className="ant-upload-text">点击上传图片</div>
                                            </div>
                                    }
                                </Upload>
                            )}
                        </div>
                    </FormItem>
                </Form>
                {/* 预览图片对话框 */}
                <Modal visible={previewVisible} footer={null} onCancel={cancelPreview}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </Modal>
        );
    }
);
export default class PlatformBanner extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            bannerList: [],
            visible: false,
            fileList: [],
            previewVisible: false,
            previewImage: '',
            BannerId: undefined,
            openLength:0,//开启的条数
            isOpen:0,//正在更改的是否开启
        }
    }
    componentDidMount() {
        this.getBannerList();
    }
    //获取banner列表
    getBannerList() {
        $.ajax({
            url: `${config.integratedBack}/banner/findBanner `,
            type: "get",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                // console.log(JSON.stringify(res));
                if (res.code === 200) {
                    // console.log(JSON.stringify(res));
                    const bannerList1 = res.bannerinfo;
                    if (bannerList1.length > 0) {
                        let arr1=[];
                        let arr2=[];
                        bannerList1.forEach((item, index) => {
                            item.key=index+1;
                            if(item.t_state==1){
                                arr1.push(item);
                            }else{
                                arr2.push(item);
                            }
                        });
                        arr1.sort((a,b)=>a.t_sort-b.t_sort);
                        let bannerList=arr1.concat(arr2);
                        this.setState({
                            openLength:arr1.length,
                            bannerList,
                            bannercount: res.bannerinfo.length,
                        });
                    } else {
                        this.setState({
                            openLength:0,
                            bannerList:[],
                            bannercount: 0,
                        });
                    }
                }
            }
        });
    }
    //保存
    saveBanner() {
        this.bannerForm.validateFields((err, values) => {
            if (!err) {
                console.log(values);
                const { BannerId } = this.state;
                let url,
                    data = {
                        t_bannerName: values.t_bannerName,
                        t_urlPath: values.t_urlPath,
                        t_sort: values.t_sort,
                        t_imgpath: values.Filedata[0].response ? values.Filedata[0].response.data : values.Filedata[0].data,
                    };
                if (BannerId) {
                    url = `${config.integratedBack}/banner/editBanner`;
                    data.id = BannerId;
                } else {
                    url = `${config.integratedBack}/banner/addBanner`;
                }
                $.ajax({
                    url: url,
                    type: "post",
                    async: true,
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: data,
                    success: res => {
                        console.log(res);
                        if (res.code == 200) {
                            this.setState({
                                visible: false,
                                fileList: []
                            }, () => this.getBannerList())
                            this.bannerForm.resetFields();
                        } else if (res.code == 202) {
                            Modal.warning({
                                title: '保存失败',
                                content: `排序等级已存在,请另选一个排序等级`,
                            });
                        } else {
                            Modal.warning({
                                title: '保存失败',
                                content: `请返回重新操作`,
                            });
                        }
                    }
                });
            } else {
                message.error(`请填写必要的信息，再提交`, 2);
            }
        })
    }
    //新增编辑
    showBannerModal(record) {
        console.log(record);
        // console.log(record.t_state);
        if (record) {
            const { fileList } = this.state;
            console.log(fileList);
            fileList[0] = {
                uid: -1,
                name: 'abc',//随便写的
                status: 'done',
                url: record.t_imgpath
            };
            let data={
                t_bannerName: record.t_bannerName,
                t_urlPath: record.t_urlPath,
                Filedata: fileList
            };
            if(record.t_state==1){
                data.t_sort=record.t_sort;
            }
            this.setState({
                isOpen:record.t_state,
                visible: true,
                fileList,
                BannerId: record.id,
            },()=>{
                this.bannerForm.setFieldsValue(data);
            });
        } else {
            this.setState({
                visible: true,
                BannerId: undefined,
                isOpen: undefined
            });
        }
    }
    //删除数据
    deleteBaneer(record) {
        Modal.confirm({
            title: '删除Banner',
            content: '确认删除该Banner吗?',
            cancelText:'取消',
            okText:'确定',
            onCancel: () => { message.info('取消删除该Banner') },
            onOk: () => {
                let url =`${config.integratedBack}/banner/delBanner`;
                $.ajax({
                    url:url,
                    type: "GET",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        id:record.id,
                    },
                    success:data=>{
                        console.log(data);
                        if(data.code===200){
                            this.getBannerList();
                            message.success('删除成功！',1);
                        }else{
                            message.info('删除错误!',1);
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
            }
        })
    }
    //改变状态
    changeState(record,state){
        console.log(record);
        console.log(state);
        let url =`${config.integratedBack}/banner/employSetting`;
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                id:record.id,
                t_state:state,
            },
            success:data=>{
                console.log(data);
                if(data.code===200){
                    this.getBannerList();
                    message.success('修改成功！',1);
                }else{
                    message.info(data.msg,1);
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    //取消，关闭对话框
    handleCancel() {
        this.bannerForm.resetFields();
        this.setState({
            visible: false,
            fileList: []
        });
    }
    //限制用户必须上传图片格式的文件、图片大小
    beforeUpload(file, fileList) {
        let isIMG = file.type.indexOf('image') != -1;
        if (!isIMG) {
            message.config({ top: 50 });
            message.error('您只能上传图片！');
        }
        let isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
            message.config({ top: 50 });
            message.error('您上传的图片大小必须小于5MB！');
        }
        return isIMG && isLt5M;
    }
    //上传图片
    normFile(e) {
        this.setState({
            fileList: e.fileList
        });
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };
    //获取表单元素
    saveBannerFormRef(form) {
        this.bannerForm = form;
    }
    //预览图片对话框
    previewImg(file) {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    //关闭预览图片对话框
    cancelPreview() {
        this.setState({ previewVisible: false })
    }
    //同步到前端
    uploadToFront(){
        if(!this.state.openLength){
            message.info('必须开启一条Banner',1);
            return;
        }
        $.ajax({
            url: `${config.integratedBack}/banner/syncFront `,
            type: "get",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                if (res.code === 200) {
                    message.success('同步成功!',1);
                }else{
                    message.error(data.msg,1);
                }
            }
        });
    }
    render() {
        const columns = [{
            title: '排序',
            dataIndex: 't_sort',
            width: 50,
        },{
            title: '名称',
            dataIndex: 't_bannerName',
            width: 150,
        }, {
            title: '图片预览',
            dataIndex: 'imgName',
            render: (text, record) => (
                <a href={ record.t_imgpath} target="_blank">
                    <img src={ record.t_imgpath} style={{ height: "50px", width: "auto" }} />
                </a>
            ),
            width: 180,
        }, {
            title: '链接地址',
            dataIndex: 't_urlPath',
            width: 200,
        },{
            title: '状态',
            dataIndex: 't_state',
            render: (text, record) => {
                if (text ==0) {
                    return  <Button type="danger" onClick={() => this.changeState(record,0)}>停用中</Button>
                } else if (text ==1) {
                    return <Button style={{background:'rgb(60,172,208)',color:'#fff'}} onClick={() => this.changeState(record,1)}>启用中</Button>
                }
            },
            width: 50,
        }, {
            title: '操作',
            width: 100,
            render: (text, record) => (
                <span>
                    <a href="javascript:void(0);" onClick={() => this.showBannerModal(record)} style={{marginLeft:'10px'}}>编辑</a>
                    {record.t_state==1?'':<a href="javascript:void(0);" onClick={() => this.deleteBaneer(record)}  style={{marginLeft:'10px',color:'red'}}>删除</a>}
                </span>
            )
        }];
        return (
            <div className="goods-label" style={{ minWidth: 1000 }}>
                <div className="goods-label-cont clearfix">
                    <div className='goods-label-cont-nav clearfix'>
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>综合平台</Breadcrumb.Item>
                            <Breadcrumb.Item><span className='separator-a'>Banner管理</span></Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    <div className='spgl2-2 clearfix'>
                        <div className='member-content-Search'>
                            <Button className='member-button'   icon="plus" onClick={() => this.showBannerModal()}>添加</Button>
                            <Button className='member-button ' style={{float:'right'}} onClick={this.uploadToFront.bind(this)}>同步到前端</Button>
                        </div>
                    </div>
                    <div className='allgoods-table clearfix'>
                        <Table
                            className="floor-table"
                            rowKey="key"
                            columns={columns}
                            dataSource={this.state.bannerList}
                            pagination={false}
                            bordered
                        />
                    </div>
                    <BannerForm
                        visible={this.state.visible}
                        BannerId={this.state.BannerId}
                        isOpen={this.state.isOpen}
                        openLength={this.state.openLength}
                        saveBanner={this.saveBanner.bind(this)}
                        handleCancel={this.handleCancel.bind(this)}
                        ref={this.saveBannerFormRef.bind(this)}
                        normFile={this.normFile.bind(this)}
                        beforeUpload={this.beforeUpload.bind(this)}
                        fileList={this.state.fileList}
                        previewImg={this.previewImg.bind(this)}
                        previewVisible={this.state.previewVisible}
                        cancelPreview={this.cancelPreview.bind(this)}
                        previewImage={this.state.previewImage}
                    />
                </div>
            </div>
        )
    }
}